package com.mobialia.socialmediademo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.Log;


public class TwitterProvider {
	public final static String TAG = "TwitterProvider";

    OAuthConsumer oauthConsumer = new CommonsHttpOAuthConsumer(
            // the consumer key of this app (replace this with yours)
            "RFbRzd0BzYGZjrDd02ec5g",
            // the consumer secret of this app (replace this with yours)
            "wo9lKhzwpEfdXS2Z3dO2W092W9pMoJGrc5kUsBdA");

    OAuthProvider oauthProvider = new CommonsHttpOAuthProvider(
            "http://twitter.com/oauth/request_token",
            "http://twitter.com/oauth/access_token",
            "http://twitter.com/oauth/authorize");	
    
    HttpClient client = new DefaultHttpClient();
    
    boolean authenticated;
    String accessToken, tokenSecret;
	
	public static String CALLBACK_URL = "socialmediademo://twitter";
	
	SimpleDateFormat dateFormat;
    
	public TwitterProvider(Context ctx) {
		dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy", Locale.ENGLISH);
		dateFormat.setLenient(true);
		
    	SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    	accessToken = sharedPrefs.getString("twitter_token", "");
    	tokenSecret = sharedPrefs.getString("twitter_tokenSecret", "");
    	authenticated = sharedPrefs.getBoolean("twitter_authenticated", false);
	}
    
    public void launchAuth(Context context) throws Exception {
   		Log.d(TAG, "lauchAuth");

   		String authUrl = oauthProvider.retrieveRequestToken(oauthConsumer, CALLBACK_URL);
   		
   		authenticated = false;
   		accessToken = oauthConsumer.getToken();
   		tokenSecret = oauthConsumer.getTokenSecret();
   		saveState(context);
   		
		// bring the user to authUrl
   		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND | Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
    }
    
    public void verifyLogin(String verifier, Context context) throws Exception {
    	//SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
		oauthConsumer.setTokenWithSecret(accessToken, tokenSecret);	
		oauthProvider.retrieveAccessToken(oauthConsumer, verifier);
		
		authenticated = true;
   		accessToken = oauthConsumer.getToken();
   		tokenSecret = oauthConsumer.getTokenSecret();
   		saveState(context);
    }
	
    private String httpRequest(String urlString) throws Exception {
    	Log.d(TAG, "httpRequest(" + urlString + ")");
		HttpGet request = new HttpGet(urlString);
		HttpClient httpClient = new DefaultHttpClient();
			
		// sign the request
		oauthConsumer.setTokenWithSecret(accessToken, tokenSecret);
		oauthConsumer.sign(request);

		HttpResponse response = httpClient.execute(request);

		String text = Utils.convertStreamToString(response.getEntity().getContent());
		return text;
    }
	
    private Update json2Update(JSONObject object) throws Exception {
    	JSONObject user = object.getJSONObject("user");
		Update update = new Update();
		update.setMessage(Html.fromHtml(object.getString("text")).toString());
		update.setUserId(user.getString("screen_name"));
		update.setUserName(user.getString("name"));
		update.setTimeStamp(dateFormat.parse(object.getString("created_at")).getTime());
		update.setImageUrl(user.getString("profile_image_url"));
		return update;
    }
    
    public ArrayList<Update> getUpdates() throws Exception {
    	Log.d(TAG, "getUpdates()");
    	
    	ArrayList<Update> updates = new ArrayList<Update>();
    	
		String response = httpRequest("http://api.twitter.com/1/statuses/home_timeline.json?count=100");
		if (response != null) {
				
			JSONArray array = new JSONArray(response);
			for (int i = 0; i < array.length(); i++) {
				Update update = json2Update(array.getJSONObject(i));
				updates.add(update);
			}			
		}

    	return updates;
    }
    
    public boolean isAuthenticated() {
    	return authenticated;
    }
    
    public void logout(Context context) {
    	authenticated = false;
    	saveState(context);	
    }
    
    private void saveState(Context context) {
   		Log.d(TAG, "authenticated=" + authenticated);
   		Log.d(TAG, "accessToken=" + accessToken);
   		Log.d(TAG, "tokenSecret=" + tokenSecret);
    	
    	SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
		SharedPreferences.Editor editor = sharedPrefs.edit();
		editor.putBoolean("twitter_authenticated", authenticated);
		editor.putString("twitter_token", accessToken);
		editor.putString("twitter_tokenSecret", tokenSecret);
		editor.commit();
    }
}